//
//  MomentImagesCell+ConfigureForImageItems.m
//  WeChatMoments
//
//  Created by Jiang on 2019/8/27.
//  Copyright © 2019 SilverFruity. All rights reserved.
//

#import "MomentImagesCell+ConfigureForImageItems.h"
#import "ImageCollectionLayoutCalculator.h"

@implementation MomentImagesCell (ConfigureForImageItems) 


- (NSArray<ImagesItem *> *)imageItems{
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setImageItems:(NSArray<ImagesItem *> *)imageItems{
    objc_setAssociatedObject(self, @selector(imageItems), imageItems, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)configureForImageItems:(NSArray<ImagesItem *> *)imageItems{
    self.imageCollectionView.delegate = self;
    self.imageCollectionView.dataSource = self;
    // 计算collectionView的宽高和itemSize
    ImageCollectionLayoutCalculator *calculator = [ImageCollectionLayoutCalculator calculatorWithItemCount:imageItems.count
                                                                                                cellMargin:10
                                                                                    singleItemViewMaxWidth:UIScreen.mainScreen.bounds.size.width - 100 - self.cellectionViewLeftConstraint.constant
                                                                                      fourItemViewMaxWidth:UIScreen.mainScreen.bounds.size.width - 100 - self.cellectionViewLeftConstraint.constant
                                                                                      nineItemViewMaxWidth:UIScreen.mainScreen.bounds.size.width - 44 - self.cellectionViewLeftConstraint.constant];
    self.collectionViewHeihgtConstraint.constant = [calculator viewHeight];
    self.collectionViewWidthConstraint.constant = [calculator viewHeight];
    self.flowLayout.itemSize = [calculator itemSize];
    self.flowLayout.minimumInteritemSpacing = calculator.cellMargin;
    self.flowLayout.minimumLineSpacing = calculator.cellMargin;
    self.imageItems = imageItems;
    [self.imageCollectionView reloadData];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageItems.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MomentImageCollectionViewCell" forIndexPath:indexPath];
    UIImageView *imageView = cell.contentView.subviews.firstObject;
    [imageView sp_setImageWithURL:self.imageItems[indexPath.row].url placholder:UIImageWithColor([UIColor lightGrayColor])];
    return cell;
}

@end
